#coding=utf-8
from uliweb.orm import *
from uliweb.utils.common import get_var
from uliweb.i18n import ugettext_lazy as _

def get_modified_user():
    from uliweb import request
    
    return request.user.id

class Question(Model):
    __verbose_name__ = u'问题表'
    
    requirement = Reference('requirement', verbose_name='关联准开发需求')
    task = Reference('tasks_develop', verbose_name='关联任务')
    title = Field(str, max_length=200, verbose_name='标题', required=True)
    category = Field(CHAR, max_length=1, verbose_name='分类', choices=get_var('TICKET/CATETORY'), required=True)
    content = Field(TEXT, verbose_name='问题描述', required=True)
    solve_desc = Field(TEXT, verbose_name='解决措施')
    owner = Reference('user', verbose_name='所有人', collection_name='owner_questions')
    owner_sys = Reference('system', verbose_name='所属系统', collection_name='owner_sys_questions')
    kfzx = Reference('kfzx', verbose_name='提出开发中心', collection_name='kfzx_questions')
    tx = Reference('tx', verbose_name='提出条线', collection_name='tx_questions')
    submitter = Field(str, verbose_name='提出人', max_length=60, required=True)
    submit_date = Field(datetime.date, verbose_name='提出日期', auto_now_add=True)
    assigned = Field(str, verbose_name='责任人或单位', max_length=80, required=True)
    plan_finish_date = Field(datetime.date, verbose_name='计划关闭日期', required=True)
    finish_date = Field(datetime.date, verbose_name='实际关闭日期')
    status = Field(CHAR, max_length=1, verbose_name='状态', choices=get_var('TICKET/STATUS_Q'), default='1')
    priority = Field(CHAR, max_length=1, verbose_name='优先级', choices=get_var('TICKET/PRIORITY'), default='3')
    modified_date = Field(datetime.datetime, verbose_name='修改时间', auto_now=True, auto_now_add=True)
    modified_user = Reference('user', verbose_name='修改人', default=get_modified_user, auto=True, auto_add=True)
    systems = ManyToMany('system', verbose_name='责任系统')
    planexecute = Field(int, verbose_name='关联计划执行')
    need_discuss = Field(bool, verbose_name='是否需要上会', choices=get_var('PARA/YESNO'))
    
    class AddForm:
        fields = ['category', 'title', 'content', 'submitter', 'assigned', 'status', 
            'priority', 'plan_finish_date', 'systems', 'need_discuss']
    
    class AddReqForm:
        fields = ['category', 'title', 'content', 'submitter', 'assigned', 'status', 
            'priority', 'plan_finish_date', 'owner_sys', 'systems', 'need_discuss']
    
    class EditForm:
        fields = ['category', 'title', 'content', 'submitter', 'assigned', 'status', 
            'priority', 'solve_desc', 'plan_finish_date',
            'finish_date', 'systems', 'need_discuss']
    
    class EditReqForm:
        fields = ['category', 'title', 'content', 'submitter', 'assigned', 'status', 
            'priority', 'solve_desc', 'plan_finish_date',
            'finish_date', 'owner_sys', 'systems', 'need_discuss']
    
    class SolveForm:
        fields = ['solve_desc']

    class DetailView:
        fields = ['requirement', 'task', 'category', 'title', 'content', 'submitter', 
            'submit_date', 'assigned', 'status', 
            'priority', 'progress', 'solve_desc', 'plan_finish_date',
            'systems', 'owner_sys', 'tx', 'kfzx',
            'finish_date', 'owner', 'need_discuss', 'modified_date', 'modified_user']
    
    class Table:
        fields = [
            {'name':'need_discuss', 'width':80, 'sortable':True},
            {'name':'category', 'width':40, 'sortable':True},
            {'name':'priority', 'width':50, 'sortable':True},
            {'name':'status', 'width':50, 'sortable':True},
            {'name':'progress', 'verbose_name':'进度情况', 'width':60, 'sortable':True},
            {'name':'title', 'width':200, 'sortable':True},
#            {'name':'solve_desc', 'width':200},
            {'name':'submitter', 'sortable':True},
            {'name':'submit_date', 'sortable':True},
            {'name':'assigned', 'sortable':True},
            {'name':'plan_finish_date', 'sortable':True},
            {'name':'finish_date', 'sortable':True},
            {'name':'requirement', 'width':200, 'sortable':True},
            {'name':'care_level', 'verbose_name':'关注级别', 'width':60, 'sortable':True},
            {'name':'task', 'width':200, 'sortable':True},
            {'name':'tx', 'width':60, 'sortable':True},
            {'name':'kfzx', 'width':60, 'sortable':True},
            {'name':'owner_sys', 'width':80, 'sortable':True},
            {'name':'systems', 'width':200},
        ]
        
    def __unicode__(self):
        return u"问题:%s" % self.title
    
    def get_url(self):
        return u'<a href="/ticket/q/%d" title="%s">#%d</a>' % (self.id, self.title, self.id)
    
    def get_receiver_ids(self, sender_id):
        users = set([])
        User = get_model('user')
        test_user = User.filter(User.c.department =='3')
        
        for x in self.systems.all():
            users.update(set(x.users.ids()))
        if sender_id in users:
            users.remove(sender_id)
        for row in test_user:
            if row.id in users:
                users.remove(row.id)
            
        return list(users)
    
    def is_assigned(self, user):
        return self.__class__.filter(self.__class__.systems.in_(user.users_systems.ids())).count() > 0 or self._owner_ == user.id
    
    def can_modify(self, user):
        if user.id == self._owner_:
            return True
        if user.department == '2' and user.is_gm and self._kfzx_ == user._kfzx_:
            return True
        if user.users_systems.has(self._owner_sys_):
            return True
    
class QuestionComment(Model):
    __verbose_name__ = u'问题回复表'
    
    question = Reference('question', verbose_name="关联问题")
    comment = Field(TEXT, verbose_name="解决记录")
    deleted = Field(bool, verbose_name='是否删除')
    modified_date = Field(datetime.datetime, verbose_name='修改时间', auto_now=True, auto_now_add=True)
    modified_user = Reference('user', verbose_name='修改人', default=get_modified_user)

    class AddForm:
        fields = ['comment']
    
class Risk(Model):
    __verbose_name__ = u'风险表'
    
    requirement = Reference('requirement', verbose_name='关联准开发需求')
    task = Reference('tasks_develop', verbose_name='关联任务')
    owner_sys = Reference('system', verbose_name='所属系统', collection_name='owner_sys_risks')
    kfzx = Reference('kfzx', verbose_name='提出开发中心', collection_name='kfzx_risks')
    tx = Reference('tx', verbose_name='提出条线', collection_name='tx_risks')
    title = Field(str, max_length=200, verbose_name='标题', required=True)
    category = Field(CHAR, max_length=1, verbose_name='分类', choices=get_var('TICKET/CATETORY'), required=True)
    content = Field(TEXT, verbose_name='风险描述', required=True)
    affect = Field(TEXT, verbose_name='影响结果', required=True)
    solve_desc = Field(TEXT, verbose_name='缓解计划')
    resolusion = Field(TEXT, verbose_name='最终应对方案')
    probability = Field(DECIMAL, verbose_name='概率', precision=2, scale=1, 
        choices=get_var('TICKET/PROBABILITY'), required=True,
        hint='定性分析概率，可能性大选0.9，较大选0.7，一般选0.5，可能性小选0.3，极小选0.1')
    owner = Reference('user', verbose_name='所有人', collection_name='owner_risks')
    submitter = Field(str, verbose_name='提出人', max_length=60, required=True)
    submit_date = Field(datetime.date, verbose_name='提出日期', auto_now_add=True)
    assigned = Field(str, verbose_name='责任人或单位', max_length=80, required=True)
    status = Field(CHAR, max_length=1, verbose_name='状态', choices=get_var('TICKET/STATUS_R'), default='1')
    serious = Field(DECIMAL, verbose_name='严重性', 
        choices=get_var('TICKET/SERIOUS'), required=True, precision=2, scale=1,
        hint='定性分析严重性，严重选1，较严重选0.8，一般选0.6，不太严惩选0.4，轻微选0.2')
    systems = ManyToMany('system', verbose_name='责任系统')
    modified_date = Field(datetime.datetime, verbose_name='修改时间', auto_now=True, auto_now_add=True)
    modified_user = Reference('user', verbose_name='修改人', default=get_modified_user, auto=True, auto_add=True)
    need_discuss = Field(bool, verbose_name='是否需要上会', choices=get_var('PARA/YESNO'))
    
    class AddForm:
        fields = ['category', 'status', 'title', 'content', 'affect', 'submitter', 'assigned', 
            'probability', 'serious', 'systems', 'need_discuss']
    
    class AddReqForm:
        fields = ['category', 'status', 'title', 'content', 'affect', 'submitter', 'assigned', 
            'probability', 'serious', 'owner_sys', 'systems', 'need_discuss']

    class EditForm:
        fields = ['category', 'status', 'title', 'content', 'affect', 'submitter', 'assigned', 
            'solve_desc', 'resolusion', 'probability', 'serious', 'systems', 'need_discuss']

    class EditReqForm:
        fields = ['category', 'status', 'title', 'content', 'affect', 'submitter', 'assigned', 
            'solve_desc', 'resolusion', 'probability', 'serious', 'owner_sys', 'systems', 'need_discuss']

    class SolveForm:
        fields = ['solve_desc', 'resolusion']

    class DetailView:
        fields = ['requirement', 'task', 'category', 'title', 'content', 
            'affect', 'solve_desc', 'resolusion', 'probability', 'serious', 
            'owner', 'submitter', 'submit_date', 'assigned', 'status', 
            'systems', 'owner_sys', 'modified_date', 'modified_user', 'tx', 'kfzx', 'need_discuss']
    
    class Table:
        fields = [
            {'name':'need_discuss', 'width':80, 'sortable':True},
            {'name':'category', 'width':40, 'sortable':True},
            {'name':'status', 'width':40, 'sortable':True},
            {'name':'degree', 'verbose_name':'暴光度', 'width':50, 'sortable':True},
            {'name':'title', 'width':200, 'sortable':True},
#            {'name':'affect', 'width':200},
            {'name':'submitter', 'sortable':True},
            {'name':'submit_date', 'sortable':True},
            {'name':'assigned', 'sortable':True},
#            {'name':'solve_desc', 'width':200},
#            {'name':'resolusion', 'width':200},
            {'name':'probability', 'width':40, 'sortable':True},
            {'name':'serious', 'width':50, 'sortable':True},
            {'name':'care_level', 'verbose_name':'关注级别', 'width':60, 'sortable':True},
            {'name':'requirement', 'width':200, 'sortable':True},
            {'name':'task', 'width':200, 'sortable':True},
            {'name':'tx', 'width':60, 'sortable':True},
            {'name':'kfzx', 'width':60, 'sortable':True},
            {'name':'owner_sys', 'width':80, 'sortable':True},
            {'name':'systems', 'width':200},
        ]
        
    def __unicode__(self):
        return u"风险:%s" % self.title
    
    def get_url(self):
        return u'<a href="/ticket/q/%d" title="%s">#%d</a>' % (self.id, self.title, self.id)
    
    def get_receiver_ids(self, sender_id):
        users = set([])
        User = get_model('user')
        test_user = User.filter(User.c.department =='3')
        
        for x in self.systems.all():
            users.update(set(x.users.ids()))
        if sender_id in users:
            users.remove(sender_id)
        for row in test_user:
            if row.id in users:
                users.remove(row.id)
            
        return list(users)
    
    def is_assigned(self, user):
        return self.__class__.filter(self.__class__.systems.in_(user.users_systems.ids())).count() > 0 or self._owner_ == user.id
    
    def can_modify(self, user):
        if user.id == self._owner_:
            return True
        if user.department == '2' and user.is_gm and self._kfzx_ == user._kfzx_:
            return True
        if user.users_systems.has(self._owner_sys_):
            return True
    
class RiskComment(Model):
    __verbose_name__ = u'风险回复表'
    
    risk = Reference('risk', verbose_name="关联风险")
    comment = Field(TEXT, verbose_name="解决内容")
    deleted = Field(bool, verbose_name='是否删除')
    modified_date = Field(datetime.datetime, verbose_name='修改时间', auto_now=True, auto_now_add=True)
    modified_user = Reference('user', verbose_name='修改人', default=get_modified_user)

    class AddForm:
        fields = ['comment']
    